<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:file:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:file:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:file:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="fileList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件名" align="center" prop="filename">
        <template slot-scope="scope">
          <a :href="scope.row.filepath" target="_blank">
            {{ formatFileName(scope.row.filename) }}
          </a>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:file:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上传资料" prop="file">
          <el-upload
            class="upload-demo"
            action="/prod-api/file/uploadfile"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :multiple="false"
            :file-list="file"
            :headers="{ Authorization: getToken() }"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, delFile, dataDownloadUploadFile } from "@/api/system/file";
import { getToken } from "@/utils/auth";

export default {
  name: "File",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        filename: null,
        filepath: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      file: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getToken() {
      return getToken();
    },
    // 文件上传
    handleRemove(file, fileList) {
      this.file = [];
    },
    handleChange(file, fileList) {
      this.file = [file.raw];
    },
    // 过滤文件名
    formatFileName(filename) {
      const extension = filename.substring(filename.lastIndexOf(".") + 1);
      const originName = filename.substring(0, filename.lastIndexOf("_"));
      return `${originName}.${extension}`;
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then((response) => {
        this.fileList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        filename: null,
        filepath: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        available: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增文件";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (!this.file.length) {
            this.$modal.msgError("请先上传文件！");
            return;
          }
          const formData = new FormData();
          formData.append("file", this.file[0]);
          const res = await dataDownloadUploadFile(formData);
          if (res.code === 200) {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            this.file = [];
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除选中的数据项？")
        .then(function () {
          return delFile(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/file/export",
        {
          ...this.queryParams,
        },
        `file_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
